public class Solution19 {
    class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    private int getListLen(ListNode head){
        int len = 0;
        for(ListNode tmpNode = head; tmpNode != null; tmpNode = tmpNode.next){
            len++;
        }
        return len;
    }

    private ListNode removeIndNode(ListNode head, int removeInd){
        if(removeInd == 0){
            return head.next;
        }
        ListNode target = head;
        for (int i = 0; i < removeInd - 1; i++) {
            target = target.next;
        }
        target.next = target.next.next;
        return head;
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        return removeIndNode(head, getListLen(head) - n);
    }
}
